package com.getpebble.android.framework.endpoint;

import com.getpebble.android.bluetooth.protocol.ProtocolMessage;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.model.PblDevice;
import com.getpebble.android.framework.comm.MessageRouter;
import com.getpebble.android.framework.protocol.outbound.PblOutboundMessage;

public abstract class EndpointSet implements IEndpointMessageSender {
    private static final String TAG = EndpointSet.class.getSimpleName();
    private boolean mActive = false;
    private final MessageRouter mMessageRouter;

    public abstract boolean handleMessage(ProtocolMessage protocolMessage);

    protected abstract void onDestroy();

    protected abstract void onInit();

    public abstract void onMessageSendFailed();

    public abstract void onMessageSendSuccess();

    protected EndpointSet(MessageRouter router) {
        if (router == null) {
            throw new IllegalArgumentException("'router' cannot be null!");
        }
        this.mMessageRouter = router;
    }

    public final synchronized void destroy() {
        Trace.debug(TAG, "Destroy endpoint set: " + getClass().getSimpleName());
        this.mActive = false;
        onDestroy();
    }

    public final synchronized void init() {
        Trace.debug(TAG, "Init endpoint set: " + getClass().getSimpleName());
        this.mActive = true;
        onInit();
    }

    public final synchronized boolean sendMessage(PblOutboundMessage message) {
        boolean sendMessage;
        if (this.mActive) {
            sendMessage = this.mMessageRouter.getMessageSender(this).sendMessage(message);
        } else {
            Trace.debug(TAG, "blocking message; endpoint not active");
            sendMessage = false;
        }
        return sendMessage;
    }

    public final PblDevice getDevice() {
        return this.mMessageRouter.getDevice();
    }

    protected final boolean isActive() {
        return this.mActive;
    }
}
